#include "AlarmController.h"
#include "utils/Logger.h"
#include <QDebug>

AlarmController::AlarmController(QObject *parent)
    : QObject(parent),
      m_alarmModel(nullptr),
      m_dataRecordModel(nullptr),
      m_config(nullptr),
      m_alarmDetectionEnabled(true),
      m_unacknowledgedCount(0),
      m_criticalAlarmCount(0),
      m_warningAlarmCount(0)
{
}

AlarmController::~AlarmController()
{
}

// 设置报警模型
void AlarmController::setAlarmModel(AlarmModel *model)
{
    m_alarmModel = model;

    if (m_alarmModel)
    {
        // 连接模型信号
        connect(m_alarmModel, &AlarmModel::countChanged,
                this, &AlarmController::onAlarmModelCountChanged);
        connect(m_alarmModel, &AlarmModel::unacknowledgedCountChanged,
                this, &AlarmController::onAlarmModelCountChanged);

        // 初始化统计
        updateAlarmCounts();
    }

    qDebug() << "AlarmController: 设置 AlarmModel";
}

// 设置实时数据模型
void AlarmController::setDataRecordModel(DataRecordModel *model)
{
    m_dataRecordModel = model;

    if (m_dataRecordModel)
    {
        // 监听数据更新
        connect(m_dataRecordModel, &DataRecordModel::dataUpdated,
                this, &AlarmController::onDataUpdated);
    }

    qDebug() << "AlarmController: 设置 DataRecordModel";
}

// 设置配置管理器
void AlarmController::setConfig(Config *config)
{
    m_config = config;
    qDebug() << "AlarmController: 设置 Config";
}

// 获取未确认报警数量
int AlarmController::unacknowledgedCount() const
{
    return m_unacknowledgedCount;
}

// 获取严重报警数量
int AlarmController::criticalAlarmCount() const
{
    return m_criticalAlarmCount;
}

// 获取警告报警数量
int AlarmController::warningAlarmCount() const
{
    return m_warningAlarmCount;
}

// 设置报警检测开关
void AlarmController::setAlarmDetectionEnabled(bool enabled)
{
    if (m_alarmDetectionEnabled == enabled)
        return;

    m_alarmDetectionEnabled = enabled;
    emit alarmDetectionEnabledChanged();

    qInfo() << "AlarmController: 报警检测" << (enabled ? "启用" : "禁用");
    Logger::instance()->logOperation("alarm_detection", "system",
                                     enabled ? "启用报警检测" : "禁用报警检测");
}

// 加载最近的报警
bool AlarmController::loadRecentAlarms(int hours)
{
    qInfo() << "AlarmController: 加载最近" << hours << "小时报警";

    if (!m_alarmModel)
    {
        qWarning() << "AlarmController: AlarmModel 未设置";
        return false;
    }

    bool success = m_alarmModel->loadRecentAlarms(hours);
    if (success)
    {
        updateAlarmCounts();
    }

    return success;
}

// 加载未确认的报警
bool AlarmController::loadUnacknowledgedAlarms()
{
    qInfo() << "AlarmController: 加载未确认报警";

    if (!m_alarmModel)
        return false;

    bool success = m_alarmModel->loadUnacknowledgedAlarms();
    if (success)
    {
        updateAlarmCounts();
    }

    return success;
}

// 加载指定设备的报警
bool AlarmController::loadAlarmsForDevice(const QString &deviceId)
{
    qInfo() << "AlarmController: 加载设备报警 -" << deviceId;

    if (!m_alarmModel)
        return false;

    bool success = m_alarmModel->loadAlarmsForDevice(deviceId);
    if (success)
    {
        updateAlarmCounts();
    }

    return success;
}

// 加载指定级别的报警
bool AlarmController::loadAlarmsByLevel(const QString &level)
{
    qInfo() << "AlarmController: 加载级别报警 -" << level;

    if (!m_alarmModel)
        return false;

    bool success = m_alarmModel->loadAlarmsByLevel(level);
    if (success)
    {
        updateAlarmCounts();
    }

    return success;
}

// 加载日期范围内的报警
bool AlarmController::loadAlarmsDateRange(const QDateTime &start, const QDateTime &end)
{
    qInfo() << "AlarmController: 加载日期范围报警";

    if (!m_alarmModel)
        return false;

    bool success = m_alarmModel->loadAlarmsDateRange(start, end);
    if (success)
    {
        updateAlarmCounts();
    }

    return success;
}

// 确认报警
bool AlarmController::acknowledgeAlarm(int index, const QString &userName)
{
    qInfo() << "AlarmController: 确认报警 - 索引:" << index << "用户:" << userName;

    if (!m_alarmModel)
        return false;

    bool success = m_alarmModel->acknowledgeAlarm(index, userName);
    if (success)
    {
        updateAlarmCounts();
        emit alarmAcknowledged(m_alarmModel->getAlarmRecord(index).id());
        Logger::instance()->logOperation("acknowledge_alarm", "alarm",
                                         QString("确认报警，索引: %1").arg(index), userName);
    }

    return success;
}

// 根据ID确认报警
bool AlarmController::acknowledgeAlarmById(int alarmId, const QString &userName)
{
    qInfo() << "AlarmController: 确认报警 - ID:" << alarmId << "用户:" << userName;

    if (!m_alarmModel)
        return false;

    bool success = m_alarmModel->acknowledgeAlarmById(alarmId, userName);
    if (success)
    {
        updateAlarmCounts();
        emit alarmAcknowledged(alarmId);
        Logger::instance()->logOperation("acknowledge_alarm", "alarm",
                                         QString("确认报警，ID: %1").arg(alarmId), userName);
    }

    return success;
}

// 确认所有报警
bool AlarmController::acknowledgeAllAlarms(const QString &userName)
{
    qInfo() << "AlarmController: 确认所有报警 - 用户:" << userName;

    if (!m_alarmModel)
        return false;

    bool success = m_alarmModel->acknowledgeAllAlarms(userName);
    if (success)
    {
        updateAlarmCounts();
        emit allAlarmsAcknowledged();
        Logger::instance()->logOperation("acknowledge_all_alarms", "alarm", "确认所有报警", userName);
    }

    return success;
}

// 删除报警
bool AlarmController::removeAlarm(int index)
{
    qInfo() << "AlarmController: 删除报警 - 索引:" << index;

    if (!m_alarmModel)
        return false;

    bool success = m_alarmModel->removeAlarm(index);
    if (success)
    {
        updateAlarmCounts();
    }

    return success;
}

// 清空所有报警
bool AlarmController::clearAllAlarms()
{
    qInfo() << "AlarmController: 清空所有报警";

    if (!m_alarmModel)
        return false;

    bool success = m_alarmModel->clearAllAlarms();
    if (success)
    {
        updateAlarmCounts();
    }

    return success;
}

// 获取温度警告阈值
double AlarmController::getTempWarningThreshold() const
{
    if (!m_config)
        return 80.0;

    return m_config->tempWarningThreshold();
}

// 获取温度严重阈值
double AlarmController::getTempCriticalThreshold() const
{
    if (!m_config)
        return 100.0;

    return m_config->tempCriticalThreshold();
}

// 获取压力警告阈值
double AlarmController::getPressureWarningThreshold() const
{
    if (!m_config)
        return 500.0;

    return m_config->pressureWarningThreshold();
}

// 获取压力严重阈值
double AlarmController::getPressureCriticalThreshold() const
{
    if (!m_config)
        return 800.0;

    return m_config->pressureCriticalThreshold();
}

// 获取流量警告阈值
double AlarmController::getFlowWarningThreshold() const
{
    if (!m_config)
        return 100.0;

    return m_config->flowWarningThreshold();
}

// 设置温度警告阈值
bool AlarmController::setTempWarningThreshold(double value)
{
    qInfo() << "AlarmController: 设置温度警告阈值 -" << value;

    if (!m_config)
        return false;

    bool success = m_config->setDouble("temp_warning_threshold", value);
    if (success)
    {
        emit thresholdChanged("temperature_warning", value);
        Logger::instance()->logOperation("set_threshold", "temperature",
                                         QString("设置温度警告阈值: %1℃").arg(value));
    }

    return success;
}

// 设置温度严重阈值
bool AlarmController::setTempCriticalThreshold(double value)
{
    qInfo() << "AlarmController: 设置温度严重阈值 -" << value;

    if (!m_config)
        return false;

    bool success = m_config->setDouble("temp_critical_threshold", value);
    if (success)
    {
        emit thresholdChanged("temperature_critical", value);
        Logger::instance()->logOperation("set_threshold", "temperature",
                                         QString("设置温度严重阈值: %1℃").arg(value));
    }

    return success;
}

// 设置压力警告阈值
bool AlarmController::setPressureWarningThreshold(double value)
{
    qInfo() << "AlarmController: 设置压力警告阈值 -" << value;

    if (!m_config)
        return false;

    bool success = m_config->setDouble("pressure_warning_threshold", value);
    if (success)
    {
        emit thresholdChanged("pressure_warning", value);
        Logger::instance()->logOperation("set_threshold", "pressure",
                                         QString("设置压力警告阈值: %1kPa").arg(value));
    }

    return success;
}

// 设置压力严重阈值
bool AlarmController::setPressureCriticalThreshold(double value)
{
    qInfo() << "AlarmController: 设置压力严重阈值 -" << value;

    if (!m_config)
        return false;

    bool success = m_config->setDouble("pressure_critical_threshold", value);
    if (success)
    {
        emit thresholdChanged("pressure_critical", value);
        Logger::instance()->logOperation("set_threshold", "pressure",
                                         QString("设置压力严重阈值: %1kPa").arg(value));
    }

    return success;
}

// 设置流量警告阈值
bool AlarmController::setFlowWarningThreshold(double value)
{
    qInfo() << "AlarmController: 设置流量警告阈值 -" << value;

    if (!m_config)
        return false;

    bool success = m_config->setDouble("flow_warning_threshold", value);
    if (success)
    {
        emit thresholdChanged("flow_warning", value);
        Logger::instance()->logOperation("set_threshold", "flow",
                                         QString("设置流量警告阈值: %1L/min").arg(value));
    }

    return success;
}

// 手动触发报警检测
void AlarmController::checkDataPoint(const QString &deviceId, double temperature, double pressure, double flow)
{
    detectAlarms(deviceId, temperature, pressure, flow);
}

// 实时数据更新
void AlarmController::onDataUpdated()
{
    if (!m_alarmDetectionEnabled || !m_dataRecordModel)
        return;

    // 获取最新数据点
    DataPoint latestData = m_dataRecordModel->getLatestDataPoint();
    if (!latestData.isValid())
        return;

    // 触发报警检测
    detectAlarms(latestData.deviceId(),
                 latestData.temperature(),
                 latestData.pressure(),
                 latestData.flow());
}

// AlarmModel 数量变化
void AlarmController::onAlarmModelCountChanged()
{
    updateAlarmCounts();
}

// 检测报警
void AlarmController::detectAlarms(const QString &deviceId, double temperature, double pressure, double flow)
{
    if (!m_alarmDetectionEnabled)
        return;

    // 检测温度报警
    checkTemperatureAlarm(deviceId, temperature);

    // 检测压力报警
    checkPressureAlarm(deviceId, pressure);

    // 检测流量报警
    checkFlowAlarm(deviceId, flow);
}

// 检测温度报警
void AlarmController::checkTemperatureAlarm(const QString &deviceId, double temperature)
{
    if (temperature < 0)
        return;

    double warningThreshold = getTempWarningThreshold();
    double criticalThreshold = getTempCriticalThreshold();

    // 严重报警
    if (temperature >= criticalThreshold)
    {
        createAlarm(deviceId, "over_temp", "critical", "temperature",
                    temperature, criticalThreshold,
                    QString("温度严重超标: %.1f℃ (阈值: %.1f℃)").arg(temperature).arg(criticalThreshold));
    }
    // 警告报警
    else if (temperature >= warningThreshold)
    {
        createAlarm(deviceId, "over_temp", "warning", "temperature",
                    temperature, warningThreshold,
                    QString("温度超标: %.1f℃ (阈值: %.1f℃)").arg(temperature).arg(warningThreshold));
    }
}

// 检测压力报警
void AlarmController::checkPressureAlarm(const QString &deviceId, double pressure)
{
    if (pressure < 0)
        return;

    double warningThreshold = getPressureWarningThreshold();
    double criticalThreshold = getPressureCriticalThreshold();

    // 严重报警
    if (pressure >= criticalThreshold)
    {
        createAlarm(deviceId, "over_pressure", "critical", "pressure",
                    pressure, criticalThreshold,
                    QString("压力严重超标: %.1fkPa (阈值: %.1fkPa)").arg(pressure).arg(criticalThreshold));
    }
    // 警告报警
    else if (pressure >= warningThreshold)
    {
        createAlarm(deviceId, "over_pressure", "warning", "pressure",
                    pressure, warningThreshold,
                    QString("压力超标: %.1fkPa (阈值: %.1fkPa)").arg(pressure).arg(warningThreshold));
    }
}

// 检测流量报警
void AlarmController::checkFlowAlarm(const QString &deviceId, double flow)
{
    if (flow < 0)
        return;

    double warningThreshold = getFlowWarningThreshold();

    // 流量警告（只有警告级别）
    if (flow >= warningThreshold)
    {
        createAlarm(deviceId, "over_flow", "warning", "flow",
                    flow, warningThreshold,
                    QString("流量超标: %.2fL/min (阈值: %.2fL/min)").arg(flow).arg(warningThreshold));
    }
}

// 创建报警记录
bool AlarmController::createAlarm(const QString &deviceId,
                                  const QString &alarmType,
                                  const QString &alarmLevel,
                                  const QString &paramName,
                                  double paramValue,
                                  double threshold,
                                  const QString &description)
{
    if (!m_alarmModel)
        return false;

    // 添加报警记录
    bool success = m_alarmModel->addAlarmRecord(deviceId, alarmType, alarmLevel,
                                                paramName, paramValue, threshold, description);

    if (success)
    {
        qWarning() << "AlarmController: 新报警 -" << deviceId << "-" << description;
        emit newAlarm(deviceId, alarmType, alarmLevel);
        updateAlarmCounts();
    }

    return success;
}

// 更新统计计数
void AlarmController::updateAlarmCounts()
{
    if (!m_alarmModel)
        return;

    int newUnacknowledgedCount = m_alarmModel->unacknowledgedCount();
    int newCriticalCount = m_alarmModel->getCriticalAlarmCount();
    int newWarningCount = m_alarmModel->getWarningAlarmCount();

    bool changed = false;

    if (m_unacknowledgedCount != newUnacknowledgedCount)
    {
        m_unacknowledgedCount = newUnacknowledgedCount;
        emit unacknowledgedCountChanged();
        changed = true;
    }

    if (m_criticalAlarmCount != newCriticalCount)
    {
        m_criticalAlarmCount = newCriticalCount;
        emit criticalAlarmCountChanged();
        changed = true;
    }

    if (m_warningAlarmCount != newWarningCount)
    {
        m_warningAlarmCount = newWarningCount;
        emit warningAlarmCountChanged();
        changed = true;
    }

    if (changed)
    {
        qDebug() << "AlarmController: 更新统计 - 未确认:" << m_unacknowledgedCount
                 << "严重:" << m_criticalAlarmCount
                 << "警告:" << m_warningAlarmCount;
    }
}
